package com.zhs.gccs.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.orhanobut.logger.Logger;

import org.apache.commons.io.FilenameUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.Arrays;

/**
 * Created by heyang on 2017/3/6.
 */

public class FileUtils extends org.apache.commons.io.FileUtils {

    //系统sd卡路径
    //String path = Environment.getExternalStorageState();

    //程序为app分配的应用内的缓存路径
    // context.getCacheDir().getAbsolutePath()
    // /data/data/net.liulv.net.liulv.tongxinbang/cache
    private Context context;
    public static String pattern = "MM月dd日HH时mm分ss秒";
    public static String gb_pattern = "yyyy.MM.dd_HH-mm-ss";
    public static String separator = "_";
    public static String suffix = ".jpeg";
    public static String suffixBMP = ".bmp";
    public static String suffixTXT = ".txt";
    public static String suffixMP4 = ".mp4";
    public static String suffixMP3 = ".mp3";
    public static String suffixAMR = ".amr";
    public static String suffixAPK = ".apk";
    public static String suffixHTML = ".html";


    private static FileUtils instance;

    public static FileUtils getInstance(Context context) {
        if (instance == null)
            instance = new FileUtils(context);
        return instance;
    }

    private FileUtils(Context context) {
        this.context = context;
    }

    public static long getDirSize(File file) {
        long size = 0;  //文件大小
        if (file.isFile())  //如果是文件，size加上文件长度
            size += file.length();
        else {  //否则
            File[] files = file.listFiles();    //目录获取文件数组
            for (int i = 0; files != null && i < files.length; i++)
                size += getDirSize(files[i]);  //递归调用本方法
        }
        return size;
    }



    public static String readAssetFile(Context context, String srcFileName){
        try {
            ByteArrayOutputStream sr = new ByteArrayOutputStream();
            InputStream is = context.getAssets().open(srcFileName);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                sr.write(buffer, 0, byteCount);
            }
            return sr.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }






    public static File createFile(String parent, String child) {
        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        return new File(parent, child);
    }



    public static boolean deleteFile(String path) {
        boolean flag = false;
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            if (file.exists()) {
                flag = file.delete();
            }
            Logger.e("删除文件" + (flag ? "成功" : "失败"));
        }
        return flag;
    }



    // 将字符串添加写入到文本文件中
    public static void writeTxtToFile(Context mContext, String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        //makeFilePath(filePath, fileName);
//        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//        AlertDialog dialog = builder.create(); //创建对话框
//        dialog.setCanceledOnTouchOutside(false); //设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
//        dialog.show();

        String strFilePath = filePath + fileName;
        // 每次写入时，都换行写
        //String strContent = strcontent + "\r\n";
        // 每次写入时，都不换行写
        String strContent = strcontent;
        try {
            File file = new File(strFilePath);
            if (file.exists()) {
                file.delete();
            }
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            dialog.dismiss();
        }
    }




    /**
     * 根据uri拷贝文件至指定路径
     *
     * @param audioDst
     * @param uri
     */
    public static void copyUri2File(Context context, String audioDst, Uri uri) {
        try {
            AssetFileDescriptor audioAsset = context.getContentResolver()
                    .openAssetFileDescriptor(uri, "r");
            InputStream in = audioAsset.createInputStream();
            OutputStream out = new FileOutputStream(audioDst);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getFileEndName(String filePath) {
        if (filePath == null) return null;
        String fileName = null;
        int cut = filePath.lastIndexOf('/');
        if (cut != -1) {
            fileName = filePath.substring(cut + 1);
        }
        return fileName;
    }

    //保存bitmap文件
    public static void saveBitmap(Bitmap bitmap, String filePath) {
        if (filePath.contains("/")) {
            String mPath = filePath.substring(0, filePath.lastIndexOf("/"));
            File dir = new File(mPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        File f = new File(filePath);
        if (!f.exists()) {
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, out);//压缩 75%的质量
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String getExt(String fileName){
        if (fileName == null)
        {
            return null;
        }
        if(!fileName.contains(".")){
            return null;
        }
        return fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
    }

    private static final String[] ARCHIVE_TYPES = {"rar", "zip", "jar", "7-zip", "tar", "gzip", "7z"};


    private static String[] PICTURE_TYPES = {"jpg", "jpeg", "png", "gif", "bmp", "ico", "jfif", "webp"};
    public static boolean isImage(String ext) {
        if(ext==null)return false;
        if(Arrays.asList(PICTURE_TYPES).contains(ext.toLowerCase())){
            return true;
        }
        return false;
    }
    public static boolean isPDF(String ext) {
        if(ext==null)return false;
        if("pdf".equalsIgnoreCase(ext)){
            return true;
        }
        return false;
    }

    private static final String[] OFFICE_TYPES = {"docx", "wps", "doc", "docm", "xls", "xlsx", "csv" ,"xlsm", "ppt", "pptx", "vsd", "rtf", "odt", "wmf", "emf", "dps", "et", "ods", "ots", "tsv", "odp", "otp", "sxi", "ott", "vsdx", "fodt", "fods", "xltx","tga","psd","dotm","ett","xlt","xltm","wpt","dot","xlam","dotx","xla","pages"};
    public static boolean isOffice(String ext) {
        if(ext==null)return false;
        if(Arrays.asList(OFFICE_TYPES).contains(ext.toLowerCase())){
            return true;
        }
        return false;
    }

    private static final String[] CAD_TYPES = {"dwg", "dxf", "dwf"};
    public static boolean isCad(String ext) {
        if(ext==null)return false;
        if(Arrays.asList(CAD_TYPES).contains(ext.toLowerCase())){
            return true;
        }
        return false;
    }

    public static String getNameNotSuffix(String fileName)
    {
        if (fileName == null)
        {
            return null;
        }
        String baseName = FilenameUtils.getBaseName(fileName);
        return baseName;
    }
}
